package com.lagou.service;

import com.google.common.cache.LoadingCache;
import com.lagou.bean.HotPositionDto;
import com.lagou.bean.Result;
import com.lagou.pojo.HotPosition;
import com.lagou.repository.HotPositionRepository;
import com.lagou.utils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author senyang
 */
@Service
public class HotPositionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HotPositionService.class);

    @Autowired
    HotPositionRepository hotPositionRepository;

    @Autowired
    GuavaCacheService guavaCacheService;


    public Page<HotPosition> findAll(Integer pageNo,Integer pageSize){
        LOGGER.error("----------->>>> 调用mysql数据源查询数据 ------------->>>>>>>>>");
        Pageable pageable = PageRequest.of(pageNo,pageSize);

        Page<HotPosition> all = hotPositionRepository.findAll(pageable);
        List<HotPosition> content = all.getContent();
        for (HotPosition hotPosition : content) {
            String createTime = hotPosition.getCreateTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm;ss");
            Date nowDate = new Date();
            String substring = createTime.substring(0, 10);
            hotPosition.setCreateTime(substring);
        }
        return all;
    }

    public Result addHotPos(HotPositionDto dto){
        HotPosition position = new HotPosition();
        BeanUtils.copyProperties(dto,position);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm;ss");
        Date nowDate = new Date();
        position.setCreateTime(sdf.format(nowDate));
        HotPosition save = hotPositionRepository.save(position);
        guavaCacheService.removeHotPosGuavaCache();

        return Result.ok(save);
    }

    public Result delHotPos(Integer id){
        hotPositionRepository.deleteById(id);
        guavaCacheService.removeHotPosGuavaCache();
        return Result.ok();
    }


}
